package com.huixin.zhang.common.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.UUID;


public class FileUtils {

	public static String getNewFileName(String fileName){
		if(TextUtils.isBlank(fileName)){
			return null;
		}
		String uuid =  UUID.randomUUID().toString();
		uuid = uuid.replace("-", "");
		StringBuilder builder = new StringBuilder(uuid);
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		builder.append(suffix);
		return builder.toString();
	}

	/**
	 * 下载文件
	 * @param file
	 * @param newFileName
	 */
	public static ResponseEntity<byte[]> downloadFile(File file, String newFileName) {
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.add("Content-Disposition", "attachment; filename=" + new String(newFileName.getBytes("ISO-8859-1"), "UTF-8"));
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			InputStream is = new FileInputStream(file.getAbsolutePath());
			BufferedInputStream bis = new BufferedInputStream(is);
			int length = 0;
			byte[] temp = new byte[1 * 1024 * 10];
			while ((length = bis.read(temp)) != -1) {
				bos.write(temp, 0, length);
			}
			byte[] byteArray = bos.toByteArray();
			bos.flush();
			bis.close();
			bos.close();
			is.close();
			ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(byteArray, headers, HttpStatus.OK);
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
	}

	/**
	 * 将文件转换成byte数组
	 * @param
	 * @return
	 */
	public static byte[] fileToByteArray(String filePath){
		if(StringUtils.isEmpty(filePath))
			return null;
		File file = new File(filePath);
		if(!file.exists())
			return null;
		return fileToByteArray(file);
					
	}
	
	/**
	 * 将文件转换成byte数组
	 * @param
	 * @return
	 */
	public static byte[] fileToByteArray(File tradeFile){
		byte[] buffer = null;
		try
		{
			FileInputStream fis = new FileInputStream(tradeFile);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1)
			{
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		}catch (FileNotFoundException e){
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}
		return buffer;
	}
}
